package leetcode_数组.字串;

import java.util.*;

/**
 * 560.和为 K 的子数组
 * 算法：哈希表 + 前缀和
 *
 * @author yezh
 * @date 2023/12/29 15:19
 */
public class _560 {

    public int subarraySum(int[] nums, int k) {
        int ans = 0, sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int num : nums) {
            sum += num;
            ans += map.getOrDefault(sum - k, 0);
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
        return ans;
    }

    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        int[] ans = new int[n - k + 1];
        Deque<Integer> queue = new LinkedList<>();
        for (int i = 0, idx; i < n; i++) {
            while (!queue.isEmpty() && nums[i] > nums[queue.peekLast()]) queue.pollLast();
            idx = i - k + 1;
            if (queue.peekFirst() == i - 1) queue.pollFirst();
            if (idx >= 0) ans[idx] = nums[queue.peekFirst()];
        }
        return ans;
    }

}
